<template>
  <div class="warehouse-area-manage">
    <!-- 左侧仓库列表 -->
    <div class="left-panel">
      <div class="panel-header">
        <span class="title">仓库列表</span>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddWarehouse">
          新增仓库
        </el-button>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="warehouseSearchKey"
          placeholder="搜索仓库"
          prefix-icon="el-icon-search"
          clearable
          @input="handleWarehouseSearch"
        />
      </div>

      <!-- 仓库列表 -->
      <div class="warehouse-list">
        <div
          v-for="item in filteredWarehouseList"
          :key="item.stoId"
          :class="['warehouse-item', { 'active': selectedWarehouse && selectedWarehouse.stoId === item.stoId, 'disabled': item.enableState === '0' }]"
        >
          <div class="warehouse-icon" @click="handleSelectWarehouse(item)">
            <img v-if="item.picPath" :src="item.picPath" :alt="item.stoName" @error="handleImageError" />
            <i v-else class="el-icon-office-building"></i>
          </div>
          <div class="warehouse-info" @click="handleSelectWarehouse(item)">
            <div class="warehouse-name">{{ item.stoName }}</div>
            <div class="warehouse-code">编码: {{ item.stoCode }}</div>
            <div class="warehouse-address">地址: {{ item.address || '暂无' }}</div>
            <div class="warehouse-type">类型: {{ item.picClassName || '综合仓' }}</div>
          </div>
          <div class="warehouse-actions">
            <el-tooltip content="编辑" placement="top">
              <el-button type="text" icon="el-icon-edit" size="mini" @click.stop="handleEditWarehouse(item)"></el-button>
            </el-tooltip>
            <el-tag size="mini" :type="item.enableState === '1' ? 'success' : 'danger'">
              {{ item.enableState === '1' ? '启用' : '停用' }}
            </el-tag>
          </div>
        </div>

        <div v-if="filteredWarehouseList.length === 0" class="empty-data">
          <i class="el-icon-folder-opened"></i>
          <p>暂无仓库数据</p>
        </div>
      </div>
    </div>

    <!-- 右侧库区列表 -->
    <div class="right-panel">
      <div class="panel-header">
        <span class="title">
          {{ selectedWarehouse ? selectedWarehouse.stoName + ' - 库区管理' : '请选择仓库' }}
        </span>
        <div v-if="selectedWarehouse">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddArea">
            新增库区
          </el-button>
          <el-button type="default" size="small" icon="el-icon-refresh" @click="refreshAreaList">
            刷新
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div v-if="selectedWarehouse" class="filter-box">
        <el-form :inline="true" :model="areaQueryForm" size="small">
          <el-form-item>
            <el-input
              v-model="areaQueryForm.areaName"
              placeholder="库区名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleAreaQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleAreaReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 库区表格 -->
      <div v-if="selectedWarehouse" class="area-table">
        <el-table
          :data="areaList"
          border
          stripe
          v-loading="areaLoading"
          :cell-style="{ padding: '8px 0' }"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="stoAreaCode" label="库区编码"  align="center" />
          <el-table-column prop="stoAreaName" label="库区名称" align="center" />
          <el-table-column prop="temperature" label="温度"  align="center">
            <template slot-scope="scope">
              {{ scope.row.temperature || '常温' }}
            </template>
          </el-table-column>
          <el-table-column label="货位统计" width="150" align="center">
            <template slot-scope="scope">
              <span style="color: #67C23A;">启用: {{ scope.row.usedUnit || 0 }}</span> /
              <span style="color: #909399;">未启用: {{ scope.row.unusedUnit || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="状态"align="center">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleToggleAreaStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right" align="center">
            <template slot-scope="scope">
              <div class="action-buttons">
                <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditArea(scope.row)">编辑</el-button>
                <el-button type="text" size="small" icon="el-icon-box" @click="handleViewFormulations(scope.row)">分类</el-button>
                <el-button type="text" size="small" icon="el-icon-location" @click="handleViewLocations(scope.row)">货位</el-button>
                <el-button type="text" size="small" icon="el-icon-delete" style="color: #F56C6C;" @click="handleDeleteArea(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="areaTotal > 0"
          class="pagination"
          @size-change="handleAreaSizeChange"
          @current-change="handleAreaCurrentChange"
          :current-page="areaQueryForm.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="areaQueryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="areaTotal"
        />
      </div>

      <!-- 未选择仓库提示 -->
      <div v-else class="empty-placeholder">
        <i class="el-icon-warning-outline"></i>
        <p>请先在左侧选择一个仓库</p>
      </div>
    </div>

    <!-- 仓库对话框 -->
    <WarehouseDialog ref="warehouseDialogRef" :visible.sync="warehouseDialogVisible" @success="handleWarehouseSuccess" />

    <!-- 库区对话框 -->
    <AreaDialog ref="areaDialogRef" :visible.sync="areaDialogVisible" @success="handleAreaSuccess" />

    <!-- 货位管理对话框 -->
    <LocationDialog :visible.sync="locationDialogVisible" :area-info="selectedArea" />

    <!-- 剂型管理对话框 -->
    <FormulationDialog ref="formulationDialogRef" :visible.sync="formulationDialogVisible" :area-info="selectedArea" @view-locations="handleFormulationViewLocations" />
  </div>
</template>

<script>
import {
  allList,
  queryAreaByStoId,
  getAllWarehouseList,
  updateStoAreaState
} from "@/api/index/yxl";
import { deleteStoArea } from "@/api/index/warehouse";
import WarehouseDialog from "./components/WarehouseDialog.vue";
import AreaDialog from "./components/AreaDialog.vue";
import LocationDialog from "./components/LocationDialog.vue";
import FormulationDialog from "./components/FormulationDialog.vue";

export default {
  name: "WarehouseAreaManage",
  components: {
    WarehouseDialog,
    AreaDialog,
    LocationDialog,
    FormulationDialog
  },
  data() {
    return {
      // 仓库相关
      warehouseList: [],
      filteredWarehouseList: [],
      selectedWarehouse: null,
      warehouseSearchKey: '',

      // 库区相关
      areaList: [],
      areaTotal: 0,
      areaLoading: false,
      areaQueryForm: {
        areaName: '',
        pageNum: 1,
        pageSize: 20
      },

      // 对话框相关
      warehouseDialogVisible: false,
      warehouseDialogType: 'add',
      areaDialogVisible: false,
      areaDialogType: 'add',
      locationDialogVisible: false,
      formulationDialogVisible: false,
      selectedArea: {}
    };
  },
  created() {
    this.getWarehouseList();
  },
  methods: {
    // 将后端返回的相对路径转换为可访问的完整URL
    getIconUrl(path) {
      if (!path) return '';
      // 已经是完整URL
      if (/^https?:\/\//i.test(path)) return path;
      // 兼容以/开头或不以/开头的路径
      const base = process.env.VUE_APP_BASE_API || '';
      if (!base) return path;
      if (base.endsWith('/') && path.startsWith('/')) {
        return base + path.substring(1);
      }
      if (!base.endsWith('/') && !path.startsWith('/')) {
        return base + '/' + path;
      }
      return base + path;
    },

    // 获取仓库列表
    async getWarehouseList() {
      try {
        const res = await allList({});
        console.log('仓库列表完整响应:', res);
        console.log('res.rows:', res.rows);
        console.log('res.data:', res.data);
        console.log('res.total:', res.total);

        // 尝试从rows或data中获取数据
        this.warehouseList = res.rows || res.data || [];
        console.log('解析后的仓库列表:', this.warehouseList);
        console.log('第一个仓库数据:', this.warehouseList[0]);

        this.filteredWarehouseList = this.warehouseList;

        // 默认选中第一个启用的仓库
        if (this.warehouseList.length > 0) {
          const firstEnabledWarehouse = this.warehouseList.find(item => item.enableState === '1');
          if (firstEnabledWarehouse) {
            this.handleSelectWarehouse(firstEnabledWarehouse);
          } else {
            this.handleSelectWarehouse(this.warehouseList[0]);
          }
        }
      } catch (error) {
        this.$message.error('获取仓库列表失败');
      }
    },

    // 搜索仓库
    handleWarehouseSearch() {
      if (!this.warehouseSearchKey) {
        this.filteredWarehouseList = this.warehouseList;
      } else {
        const keyword = this.warehouseSearchKey.toLowerCase();
        this.filteredWarehouseList = this.warehouseList.filter(item => {
          return (
            item.stoName.toLowerCase().includes(keyword) ||
            item.stoCode.toLowerCase().includes(keyword)
          );
        });
      }
    },

    // 图片加载失败时显示默认图标
    handleImageError(e) {
      console.log('图片加载失败:', e.target.src);
      e.target.style.display = 'none';
      e.target.nextElementSibling && (e.target.nextElementSibling.style.display = 'block');
    },

    // 选择仓库
    handleSelectWarehouse(warehouse) {
      if (warehouse.enableState === '0') {
        this.$message.warning('该仓库已停用');
        return;
      }
      this.selectedWarehouse = warehouse;
      this.getAreaList();
    },

    // 获取库区列表
    async getAreaList() {
      if (!this.selectedWarehouse) return;

      this.areaLoading = true;
      try {
        const form = {
          stoId: this.selectedWarehouse.stoId
        };
        const res = await queryAreaByStoId(form);
        this.areaList = res.data || [];
        this.areaTotal = this.areaList.length;
      } catch (error) {
        this.$message.error('获取库区列表失败');
      } finally {
        this.areaLoading = false;
      }
    },

    // 刷新库区列表
    refreshAreaList() {
      this.getAreaList();
    },

    // 库区查询
    handleAreaQuery() {
      // 根据查询条件过滤
      this.getAreaList();
    },

    // 重置库区查询
    handleAreaReset() {
      this.areaQueryForm.areaName = '';
      this.getAreaList();
    },

    // 分页
    handleAreaSizeChange(val) {
      this.areaQueryForm.pageSize = val;
      this.getAreaList();
    },

    handleAreaCurrentChange(val) {
      this.areaQueryForm.pageNum = val;
      this.getAreaList();
    },

    // 新增仓库
    handleAddWarehouse() {
      this.warehouseDialogVisible = true;
      this.warehouseDialogType = 'add';
      this.$nextTick(() => {
        this.$refs.warehouseDialogRef && this.$refs.warehouseDialogRef.openDialog('add', null);
      });
    },

    // 编辑仓库
    handleEditWarehouse(warehouse) {
      this.warehouseDialogVisible = true;
      this.warehouseDialogType = 'edit';
      this.$nextTick(() => {
        this.$refs.warehouseDialogRef && this.$refs.warehouseDialogRef.openDialog('edit', warehouse);
      });
    },

    // 新增库区
    handleAddArea() {
      if (!this.selectedWarehouse) {
        this.$message.warning('请先选择仓库');
        return;
      }
      this.areaDialogVisible = true;
      this.areaDialogType = 'add';
      this.$nextTick(() => {
        this.$refs.areaDialogRef && this.$refs.areaDialogRef.openDialog('add', null, this.selectedWarehouse.stoId);
      });
    },

    // 编辑库区
    handleEditArea(row) {
      this.areaDialogVisible = true;
      this.areaDialogType = 'edit';
      this.$nextTick(() => {
        this.$refs.areaDialogRef && this.$refs.areaDialogRef.openDialog('edit', row, this.selectedWarehouse.stoId);
      });
    },

    // 切换库区状态
    handleToggleAreaStatus(row) {
      const newStatus = row.enableState === '1' ? '0' : '1';
      const action = newStatus === '1' ? '启用' : '停用';

      updateStoAreaState({
        id: row.stoAreaId,
        enableState: newStatus
      }).then(() => {
        this.$message.success(`${action}成功`);
        this.getAreaList();
      }).catch(() => {
        this.$message.error(`${action}失败`);
      });
    },

    // 删除库区
    handleDeleteArea(row) {
      this.$confirm('确定要删除该库区吗？删除后不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStoArea({ id: row.id }).then(() => {
          this.$message.success('删除成功');
          this.getAreaList();
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },

    // 仓库对话框成功回调
    handleWarehouseSuccess() {
      this.warehouseDialogVisible = false;
      this.getWarehouseList();
    },

    // 库区对话框成功回调
    handleAreaSuccess() {
      this.areaDialogVisible = false;
      this.getAreaList();
    },

    // 查看库区剂型
    handleViewFormulations(row) {
      this.selectedArea = row;
      this.$refs.formulationDialogRef.getList(row.stoAreaId);
      this.formulationDialogVisible = true;
    },

    // 从剂型管理查看货位
    handleFormulationViewLocations(formulation) {
      this.formulationDialogVisible = false;
      this.locationDialogVisible = true;
    },

    // 查看库区货位
    handleViewLocations(row) {
      this.selectedArea = row;
      this.locationDialogVisible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.warehouse-area-manage {
  display: flex;
  height: 100%;
  background: #f0f2f5;
  gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  overflow: hidden;
}

// 左侧仓库列表
.left-panel {
  width: 320px;
  min-width: 320px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .panel-header {
    padding: 16px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .search-box {
    padding: 12px 16px;
    border-bottom: 1px solid #e8e8e8;
  }

  .warehouse-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    min-height: 0;

    .warehouse-item {
      padding: 12px;
      margin-bottom: 8px;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      gap: 12px;
      align-items: flex-start;

      &:hover {
        border-color: #409EFF;
        background: #f5f7fa;
      }

      &.active {
        border-color: #409EFF;
        background: #ecf5ff;
      }

      &.disabled {
        opacity: 0.5;
        cursor: not-allowed;

        &:hover {
          border-color: #e8e8e8;
          background: #fff;
        }
      }

      .warehouse-icon {
        width: 50px;
        height: 50px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        border-radius: 4px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        i {
          font-size: 28px;
          color: #909399;
        }
      }

      .warehouse-info {
        flex: 1;
        min-width: 0;

        .warehouse-name {
          font-size: 14px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .warehouse-code,
        .warehouse-address,
        .warehouse-type {
          font-size: 12px;
          color: #666;
          margin-top: 2px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .warehouse-actions {
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 8px;

        .el-button {
          padding: 0;
          font-size: 16px;

          &:hover {
            color: #409EFF;
          }
        }
      }
    }

    .empty-data {
      text-align: center;
      padding: 60px 0;
      color: #999;

      i {
        font-size: 48px;
        margin-bottom: 12px;
      }

      p {
        font-size: 14px;
      }
    }
  }
}

// 右侧库区列表
.right-panel {
  flex: 1;
  min-width: 0;
  background: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .panel-header {
    padding: 16px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .filter-box {
    padding: 12px 16px;
    border-bottom: 1px solid #e8e8e8;
    background: #fafafa;
    flex-shrink: 0;
  }

  .area-table {
    padding: 16px;
    overflow: visible;

    ::v-deep .el-table {
      // 统一行高
      .el-table__body tr {
        height: 60px;
      }

      .el-table__row {
        td {
          padding: 8px 0;

          .cell {
            line-height: 1.5;
            word-break: break-word;
          }
        }
      }

      // 操作列按钮布局
      .action-buttons {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
        gap: 4px 8px;
        padding: 4px 0;

        .el-button {
          margin: 0;
          padding: 5px 8px;
        }
      }
    }

    .pagination {
      margin-top: 16px;
      text-align: right;
    }
  }

  .empty-placeholder {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #999;

    i {
      font-size: 64px;
      margin-bottom: 16px;
    }

    p {
      font-size: 16px;
    }
  }
}
</style>
